<script setup>
  import request from "@/utils/request";
  import { ElMessage } from "element-plus";
  import { useRoute } from "vue-router";

  const role = JSON.parse(localStorage.getItem("user")).role;
  const roleId = JSON.parse(localStorage.getItem("user")).roleId;

  let route = useRoute();
  const goodsId = route.query.goodsId;
  const goods = ref({});
  const roleCul = ref(true);
  const detail = ref([]);
  const style = ref([]);
  const files = ref([]);
  const styleItem = ref({});
  const styleDrawer = ref(false);
  const upload = ref(false);

  onBeforeMount(() => {
    roleCul.value = role === "manufacturer" ? false : true;
    if (goodsId === "") {
      goods.value = {
        manuId: role === "manufacturer" ? roleId : null,
        culId: role === "inheritor" ? roleId : null
      };
    } else {
      request.get(`/goods/getOne/${goodsId}`).then((res) => {
        goods.value = res.data;
        detail.value = JSON.parse(res.data.detail);
        getStyle();
      });
    }
  });

  const getStyle = () => {
    request.get(`/style/getPart/${goodsId}`).then((res) => {
      style.value = res.data;
    });
  };

  const onChange = (file, fileList) => {
    files.value.push(file.raw);
    upload.value = true;
  };

  const handleUploadImage = () => {
    const formData = new FormData();
    formData.append('file', files.value[0]);
    request.post(`/uploadImg`, formData).then((res) => {
      goods.value.cover = res.data;
      upload.value = false;
      files.value = [];
    });
  };

  const deleteDetailImage = (res) => {
    detail.value.splice(res, 1);
  };

  const addDetailImage = () => {
    for (let i in files.value) {
      const formData = new FormData();
      formData.append('file', files.value[i]);
      request.post(`/uploadImg`, formData).then((res) => {
        detail.value.push(res.data);
        upload.value = false;
      });
    }
    files.value = [];
  };

  const leftMoveImage = (res) => {
    if (res === 0) { } else {
      let tmp = detail.value[res];
      detail.value[res] = detail.value[res-1];
      detail.value[res-1] = tmp;
    }
  };

  const rightMoveImage = (res) => {
    if (res === detail.value.length-1) { } else {
      let tmp = detail.value[res];
      detail.value[res] = detail.value[res+1];
      detail.value[res+1] = tmp;
    }
  };

  const handleStyleUploadImage = () => {
    const formData = new FormData();
    formData.append('file', files.value[0]);
    request.post(`/uploadImg`, formData).then((res) => {
      styleItem.value.styleImage = res.data;
      upload.value = false;
      files.value = [];
    });
  };

  const updateStyle = (res) => {
    styleItem.value = JSON.parse(JSON.stringify(style.value[res]));
    styleDrawer.value = true;
  };

  const insertStyle = () => {
    styleItem.value = {
      goodsId: goodsId
    };
    styleDrawer.value = true;
  };

  const deleteStyle = (index, id) => {
    style.value.splice(index, 1);
    request.delete(`/style/deleteOne/` + id).then((res) => {
      if (res.code == -1) {
        ElMessage.warning(res.msg);
      } else {
        ElMessage.success("添加样式信息成功");
        getStyle();
      }
    });
  };

  const styleSubmit = (res) => {
    if (styleItem.value.styleId === undefined) {
      request.post(`/style/insertOne`, res).then((res) => {
        if (res.code == -1) {
          ElMessage.warning(res.msg);
        } else {
          ElMessage.success("添加样式信息成功");
          getStyle();
        }
      });
    } else {
      res.goodsId = goodsId;
      request.put(`/style/updateOne`, res).then((res) => {
        if (res.code == -1) {
          ElMessage.warning(res.msg);
        } else {
          ElMessage.success("更新样式信息成功");
          getStyle();
        }
      });
    }
  }

  const goodsSubmit = () => {
    goods.value.detail = JSON.stringify(detail.value);
    if (goodsId === "") {
      request.post(`/goods/insertOne`, goods.value).then((res) => {
        if (res.code == -1) {
          ElMessage.warning(res.msg);
        } else {
          ElMessage.success("增加商品成功");
        }
      })
    } else {
      request.put(`/goods/updateOne`, goods.value).then((res) => {
        if (res.code == -1) {
          ElMessage.warning(res.msg);
        } else {
          ElMessage.success("更新商品信息成功");
        }
      })
    }
  }
</script>

<template>
  <div class="main">
    <el-form :model="goods" label-width="120px">
      <div style="display: flex; justify-content: space-between;">
        <!-- 上传封面 -->
        <div style="width: 10%; display: flex; flex-direction: column;">
          <img :src="goods.cover"
            style="box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 2px 6px 2px;" />
          <el-button v-show="!upload" style="margin-top: 5px;">
            <el-upload accept="image/jpeg,image/gif,image/png" :file-list="files" :auto-upload='false'
              :show-file-list="false" :on-change="onChange">
              选择封面
            </el-upload>
          </el-button>
          <el-button style="margin-top: 5px;" @click="handleUploadImage" v-show="upload">上传封面</el-button>
        </div>
        <!-- 基本信息 -->
        <div style="width: 80%; display: flex; flex-direction: column; justify-content: space-around;">
          <el-form-item label="标题：">
            <el-input v-model="goods.introduction" />
          </el-form-item>
          <el-form-item label="关键字：">
            <el-input v-model="goods.keyword" />
          </el-form-item>
          <div style="display: flex;">
            <el-form-item label="分类：">
              <el-input v-model="goods.sort" />
            </el-form-item>
            <el-form-item label="封面价格：">
              <el-input v-model="goods.coverPrice" />
            </el-form-item>
            <el-form-item label="联名遗产：" v-show="!roleCul">
              <el-input v-model="goods.culId" />
            </el-form-item>
            <el-form-item label="联名商家：" v-show="roleCul">
              <el-input v-model="goods.manuId" />
            </el-form-item>
            <el-button type="primary" @click="goodsSubmit" style="margin-left: 20px;">提交</el-button>
          </div>
        </div>
      </div>

      <!-- 商品详情 -->
      <el-divider content-position="center">详情图片</el-divider>
      <div style="display: flex; flex-wrap: wrap; justify-content: center;  margin: 10px auto;">
        <!-- 预览详情图片 -->
        <div v-for="(image, index) in detail"
          style="width: 20%; display: flex;  flex-direction: column; align-items: center;">
          <img :src="image" style="height: 300px; width: fit-content;">
          <div style="display: flex; justify-content: space-around; margin-top: 5px; width: 100%;" class="delete">
            <el-icon :size="30" @click="leftMoveImage(index)">
              <i-ep-ArrowLeftBold />
            </el-icon>
            <el-icon :size="30" @click="deleteDetailImage(index)">
              <i-ep-Close />
            </el-icon>
            <el-icon :size="30" @click="rightMoveImage(index)">
              <i-ep-ArrowRightBold />
            </el-icon>
          </div>
        </div>
        <!-- 添加新详情图片 -->
        <div style="width: 20%; margin: auto 0; display: flex;  flex-direction: column;">
          <div class="plus">

            <el-button v-show="!upload" style="margin-top: 5px;">
              <el-upload accept="image/jpeg,image/gif,image/png" :file-list="files" :auto-upload='false'
                :multiple="true" :limit="8" :show-file-list="false" :on-change="onChange">
                <el-icon :size="30">
                  <i-ep-Plus />
                </el-icon>
              </el-upload>
            </el-button>
            <el-button style="margin-top: 5px;" @click="addDetailImage" v-show="upload">上传</el-button>
          </div>
        </div>
      </div>

      <!-- 商品样式 -->
      <el-divider content-position="center">商品样式</el-divider>
      <div>
        <el-table :data="style" height="100%" style="width: 100%;">
          <el-table-column prop="styleName" label="样式名字" />
          <el-table-column prop="stylePrice" label="样式价格" />
          <el-table-column prop="styleImage" label="样式图片" style="width: 50px;">
            <template #default="style">
              <img :src="style.row.styleImage" style="width: 50px;">
            </template>
          </el-table-column>
          <el-table-column prop="styleStock" label="样式库存" />
          <el-table-column label="默认样式">
            <template #default="style">
              {{ style.row.defaultStyle === 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="style">
              <!-- 删除确认弹出框-弹出不生效 -->
              <el-popconfirm title="确定要删除吗?" @confirm="deleteStyle(style.$index, style.row.styleId)">
                <template #reference>
                  <el-button link type="primary" size="small">删除</el-button>
                </template>
              </el-popconfirm>
              <el-button link type="primary" size="small" @click="updateStyle(style.$index)">编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="width: 100%; height: 50px; text-align: center;
              box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px;">
          <div class="plus" @click="insertStyle">
            <el-icon :size="30" style="margin-top: 10px;">
              <i-ep-Plus />
            </el-icon>
          </div>
        </div>
      </div>
    </el-form>

    <!-- 更新样式 -->
    <el-drawer v-model="styleDrawer" title="updateStaff" :with-header="false">
      <el-form :model="styleItem" label-width="120px" style="margin: 50px">
        <el-form-item label="样式名字">
          <el-input v-model="styleItem.styleName" />
        </el-form-item>
        <el-form-item label="样式价格">
          <el-input v-model="styleItem.stylePrice" />
        </el-form-item>

        <el-form-item label="样式图片">
          <img :src="styleItem.styleImage"
            style="width: 120px; box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 2px 6px 2px;" />
          <el-button v-show="!upload" style="margin-top: 5px;">
            <el-upload accept="image/jpeg,image/gif,image/png" :file-list="files" :auto-upload='false'
              :show-file-list="false" :on-change="onChange">
              选择封面
            </el-upload>
          </el-button>
          <el-button style="margin-top: 5px;" @click="handleStyleUploadImage" v-show="upload">上传封面
          </el-button>
        </el-form-item>
        <el-form-item label="样式库存">
          <el-input v-model="styleItem.styleStock" />
        </el-form-item>
        <el-form-item label="默认样式">
          <el-input v-model="styleItem.defaultStyle" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="styleSubmit(styleItem)">提交</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

  </div>
</template>

<style lang="less" scoped>
  .main {
    width: 80%;
    margin: 20px auto;
  }

  .plus {
    text-align: center;
  }

  .plus:hover {
    cursor: pointer;
    color: red;
  }

  .delete .el-icon {
    width: 30px;
    height: 30px;
    border-radius: 15px;
    box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px;
  }

  .el-icon:hover {
    cursor: pointer;
    color: red;
  }

  .el-button+.el-button {
    margin-left: 0;
  }
</style>